package cn.jbolt.ai.core.chain.node.action;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.ai.core.chain.config.AppConfigConstant;
import cn.jbolt.ai.core.chain.config.LlmConfig;
import cn.jbolt.ai.core.chain.config.RewriteNodeConfig;
import cn.jbolt.ai.app.service.AiAppService;
import cn.jbolt.ai.core.chain.ChainContext;
import cn.jbolt.ai.core.chain.node.provider.BaseNode;
import cn.jbolt.ai.core.chain.node.provider.EventNodeProvider;
import com.fasterxml.jackson.databind.JsonNode;
import com.jboltai.capability.message.AIMessage;
import com.jboltai.capability.model.JBoltAI;
import com.jboltai.event.Event;
import com.jboltai.event.ai.rewrite.AIRewritePromptEvent;
import com.jboltai.event.signal.FailEvent;
import com.jboltai.event.signal.SuccessEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class RewriteNodeProvider extends BaseNode implements EventNodeProvider<Event> {

    private static final Logger logger = LoggerFactory.getLogger(RewriteNodeProvider.class);
    @Autowired
    private AiAppService aiAppService;

    public Event provide(JsonNode nodeConfig, ChainContext context) {
        Long appId = context.getAiApp().getId();
        Long sessionId = context.getAiSession().getId();

        try {
            LlmConfig llmConfig = LlmConfig.from(nodeConfig.get(AppConfigConstant.CONFIG_TYPE_LLM));
            RewriteNodeConfig rewriteNodeConfig = RewriteNodeConfig.from(nodeConfig.get(AppConfigConstant.CONFIG_TYPE_REWRITE));

            if (rewriteNodeConfig.getLimit()<=0 ) {
                if (rewriteNodeConfig.isOutputToResponse()) {
//                    context.sendErrorMsg("请选择上下文条数");
                    logger.error("RewriteNodeProvider process 异常,异常原因: 上下文条数不可为0");

                }
                return new FailEvent("上下文条数不可为0");
            }
            //获取上下文
            List<AIMessage> messageList = aiAppService.getSessionContextMessages(sessionId, context.getRequestMsg().getId(), rewriteNodeConfig.getLimit());
            if (messageList.isEmpty()) {
                String prompt = super.generatePrompt(llmConfig, context);
                logger.warn("检测到当前会话没有上下文信息，将直接返回原提问：{}", prompt);
                if (StrUtil.isNotBlank(rewriteNodeConfig.getOutputField())) {
                    //配置项要求，把结果输出到上下文
                    context.setAttr(rewriteNodeConfig.getOutputField(), prompt);
                }
                if (rewriteNodeConfig.isOutputToResponse()) {
                    context.sendResponseMsg(prompt, llmConfig.getFormat());
                }
                return new SuccessEvent();
            }


            AIRewritePromptEvent event = JBoltAI.rewritePrompt();
            event.contextMessages(messageList);
            //设置llm参数
            super.configLlm(llmConfig, context, event);

            event.onFail((e, error) -> {
                logger.error("Rewrite节点执行中发生异常,异常原因: {}", error.getFullMsg());
            });

            event.onComplete((e) -> {
                if (e.isSuccess()) {
                    logger.debug("AI重写结果：{}" , e.getResult());
                    //事件执行成功
                    if (StrUtil.isNotBlank(rewriteNodeConfig.getOutputField())) {
                        //配置项要求，把结果输出到上下文
                        context.setAttr(rewriteNodeConfig.getOutputField(), e.getResult());
                    }
                    if (rewriteNodeConfig.isOutputToResponse()) {
                        context.sendResponseMsg(e.getResult(), llmConfig.getFormat());
                    }

                }
            });
            return event;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("RewriteNodeProvider process 异常,异常原因", e);
            //context.sendErrorMsg( "网络异常,请稍后重试....");

        }
        return null;
    }



}
